#include "settings.h"
#include "ui_settings.h"

extern QString username, password;
extern QTcpSocket *socket;

settings::settings(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::settings)
{
    ui->setupUi(this);

    this->setAttribute(Qt::WA_DeleteOnClose);

    QFile file(":/settings.qss"); // 假设style.qss位于资源文件中
    if (file.open(QFile::ReadOnly))
    {
        setStyleSheet(QString(file.readAll())); // 应用全局样式
        file.close();
    }

    setWindowFlag(Qt::FramelessWindowHint,true);//去掉主窗口的边框
    setAttribute(Qt::WA_TranslucentBackground,true);//把主窗口透明

    connect(socket, &QTcpSocket::readyRead, this, &settings::readyReadSlot);
    connect(socket, &QTcpSocket::disconnected, this, &settings::disconnectedSlot);

    socket->write((QString("select" ) + ' ' + username).toLocal8Bit());

    ui->username->setEnabled(false);
    ui->city->setEnabled(false);

    ui->username->setText(username);

    // c = new changepassword();
    // c->hide();
}

settings::~settings()
{
    qDebug()<<"settings";
    delete ui;
    // delete c;
}

void settings::on_closeButton_clicked()
{
    this->close();
}

void settings::mousePressEvent(QMouseEvent *event)
{
    if(false == ui->changecity->underMouse() && false == ui->changepassword->underMouse() &&
        false == ui->closeButton->underMouse())
        mouseOff = event->globalPos() - geometry().topLeft();
}

void settings::mouseMoveEvent(QMouseEvent *event)
{
    if(false == ui->changecity->underMouse() && false == ui->changepassword->underMouse() &&
        false == ui->closeButton->underMouse())
        this->move(event->globalPos() - mouseOff);
}

void settings::readyReadSlot()
{
    QString str = QString::fromLocal8Bit(socket->readAll());
    if("change success" == str || "change password success" == str || "change city success" == str)
    {
        qDebug()<<str;
    }
    else
    {
        ui->city->setText(str);
    }
}

void settings::disconnectedSlot()
{

}

void settings::changePassword(QString password)
{
    socket->write((QString("changeP") + ' ' + username + ' ' + password).toLocal8Bit());
    ::password = password;
}

void settings::changeCity(QString City, QString code)
{
    socket->write((QString("changeC") + ' ' + username + ' ' +  City).toLocal8Bit());
    emit changeCity(code);
    ui->city->setText(City);
    qDebug()<<code;
}


void settings::on_changepassword_clicked()
{
    changepassword * c = new changepassword(this);
    connect(c,SIGNAL(sendClose()),this,SLOT(_close()));
    c->show();
}


void settings::on_changecity_clicked()
{
    changecity * c = new changecity(this);
    connect(c,SIGNAL(sendClose()),this,SLOT(_close()));
    c->show();
}

